package org.xukai.dal.util;

import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * Created by liumingjian on 2017/7/14.
 */
public class RaycloudDBImportUtils {

    /**
     * 通过CSV文件格式生成一条批量执行的insert into语句
     * @param csvFile
     * @return
     */
    public static String generateSqlInsert(String tableName, String csvFile) throws IOException {
        if(StringUtils.isEmpty(tableName)){
            throw new IllegalArgumentException("请设置tableName参数");
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(csvFile));
            return generateSqlInsert(tableName, reader);
        }finally{
            if(reader != null){
                reader.close();
            }
        }
    }

    public static String generateSqlInsert(String tableName, InputStream csvStream) throws IOException {
        return generateSqlInsert(tableName, new BufferedReader(new InputStreamReader(csvStream)));
    }

    public static String generateSqlInsert(String tableName, BufferedReader csvReader) throws IOException {
        if(StringUtils.isEmpty(tableName)){
            throw new IllegalArgumentException("请设置tableName参数");
        }
        String headLine = csvReader.readLine();
        if(StringUtils.isEmpty(headLine))
            throw new IllegalArgumentException("文件内容为空");

        StringBuilder sql = buildSqlHead(tableName, headLine);
        String line = null;
        int index = 0;
        while((line = csvReader.readLine()) != null){
            if(index > 0){
                sql.append(",");
            }
            sql.append("(");
            buildSqlValue(sql, line);
            sql.append(")");
            index++;
        }

        return sql.append(";").toString();
    }

    static StringBuilder buildSqlHead(String tableName, String head){
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO `").append(tableName).append("`(");
        String[] fields = head.split(",");
        for(int i = 0;i < fields.length;i++){
            if(i > 0){
                sb.append(",");
            }
            sb.append("`").append(fields[i]).append("`");
        }
        sb.append(") VALUES ");
        return sb;
    }

    static void buildSqlValue(StringBuilder sb, String line){
        String[] values = StringUtils.split(line, ",");
        // 校验values
        for(int i = 0;i < values.length;i++){
            if(values[i].startsWith("\"") || values[i].startsWith("'"))
                continue;
            values[i] = "'" + values[i] + "'";
        }
        sb.append(StringUtils.join(values, ","));
    }
}
